<template>
  <div class="login-container">
    <el-form :model="loginForm" @submit.native.prevent="handleLogin">
      <h1>教务系统登录</h1>
      <el-form-item>
        <el-input v-model="loginForm.studentId" placeholder="学号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input type="password" v-model="loginForm.password" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleLogin">登录</el-button>
      </el-form-item>
    </el-form>
    <el-checkbox v-model="adminCheckbox">管理员账号登录</el-checkbox>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { studentLoginService } from '@/api/student.js'
import { adminLoginService } from '@/api/manager.js'
import { ElMessage } from 'element-plus'
import { useUserStore, useAdminStore } from '@/stores'
const userStore = useUserStore()
const adminStore = useAdminStore()
const loginForm = reactive({
  studentId: '',
  password: ''
})
const adminCheckbox = ref(false)
const router = useRouter()
const handleLogin = async () => {
  if (adminCheckbox.value) {
    const res = await adminLoginService(loginForm)
    if (res.code === 1) {
      adminStore.setToken(res.data.token)
      ElMessage.success('管理员登录成功')
      router.push('/manager')
    } else {
      ElMessage.error('管理员登录失败')
    }
    return
  }
  const res = await studentLoginService(loginForm)
  if (res.code === 1) {
    userStore.setToken(res.data.token)
    userStore.setId(res.data.id)
    ElMessage.success('登录成功')
    router.push('/student')
  } else {
    ElMessage.error('登录失败')
  }
}
</script>

<style scoped>
.login-container {
  width: 600px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style>
